﻿using Kaskelot.SP.Model.Client;
using Kaskelot.SP.Services;
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Kaskelot.SP.UI.WebControls
{
	[ToolboxData("<{0}:ClientContextControl runat=server></{0}:ClientContextControl>")]
	public class ClientContextControl : WebControl
	{
		protected override void RenderContents(HtmlTextWriter output)
		{
			DocumentService docSvc = new DocumentService();

			Guid valDocLibId = Guid.Empty;
			string templateDocLib = string.Empty;
			string templateFolder = string.Empty;
            string byggnadDocumentFolderUrl = string.Empty;

			Guid siteId = SPContext.Current.Site.ID;            

			SPSecurity.RunWithElevatedPrivileges(delegate()
			{
				using (SPSite site = new SPSite(siteId))
				{
					bool allowUnsafe = site.RootWeb.AllowUnsafeUpdates;

					try
					{
						site.RootWeb.AllowUnsafeUpdates = true;

						valDocLibId = docSvc.EnsureDocumentLibrary(site, ApplicationContext.Current.Val).ID;
						templateDocLib = docSvc.EnsureTemplateLibrary(site).ID.ToString();
						templateFolder = docSvc.GetTemplateFolder(site).Url;

                        if (ApplicationContext.Current.Byggnad != null)
                        {
                            SPFolder docFolder = docSvc.GetByggnadFolder(site, ApplicationContext.Current.Byggnad);
                            if (docFolder != null && docFolder.Exists)
                                byggnadDocumentFolderUrl = docFolder.Url;
                        }
					}
					finally
					{
						site.RootWeb.AllowUnsafeUpdates = allowUnsafe;
					}
				}
			});

			ClientContext ctx = new ClientContext()
			{
				Val = ApplicationContext.Current.Val != null ? ApplicationContext.Current.Val.Namn : string.Empty,
				ValDocumentLibraryId = valDocLibId.ToString("B")
			};			

			ctx.TemplateLibraryId = templateDocLib;
			ctx.TemplateFolderUrl = templateFolder;
            ctx.ByggnadDocumentFolderUrl = byggnadDocumentFolderUrl;

			JavaScriptSerializer serializer = new JavaScriptSerializer();
			string json = serializer.Serialize(ctx);
			string script = "<script type\"text/javascript\">var ns = namespace(\"kaskelot.sp.ui\"); kaskelot.sp.ui.clientContext = " + json + ";</script>";
			output.Write(script);
		}
	}
}
